package com.riguz.forks.framework;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import com.riguz.gags.base.Beans;


public class BeanFactory {
    private static final ConcurrentMap<String, Object>   namedCache = new ConcurrentHashMap<String, Object>();
    private static final ConcurrentMap<Class<?>, Object> beanCache = new ConcurrentHashMap<>();
    

    @SuppressWarnings("unchecked")
    public static <T> T getInstance(String cacheKey, Class<T> defaultImplClass) {
        if (namedCache.containsKey(cacheKey)) {
            return (T) namedCache.get(cacheKey);
        }

        //TODO:defaultImplClass
        String implClassName = defaultImplClass.getName();

        T instance = Beans.newInstance(implClassName);
        if (instance != null) {
            T tmp = (T) namedCache.putIfAbsent(cacheKey, instance);
            if(tmp != null)
                instance = tmp;
        }

        return instance;
    }

    @SuppressWarnings("unchecked")
    public static <T> T getInstance(Class<T> cls){
        if (beanCache.containsKey(cls)) {
            return (T) beanCache.get(cls);
        }

        T instance = null;
        try {
                instance = cls.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        if (instance != null) {
            T tmp = (T) beanCache.putIfAbsent(cls, instance);
            if(tmp != null)
                instance = tmp;
        }

        return instance;
    }
}
